package top.infopub.mgr.mkt.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.UUID;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import top.infopub.dto.mkt.AfterSummaryDto;
import top.infopub.enums.mkt.ProProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.flow.cnst.FlowTemplateEnum;
import top.infopub.mgr.flow.service.WsFlowProcessService;
import top.infopub.mgr.mkt.dao.BidSecurityDtoDao;
import top.infopub.mgr.mkt.dao.BidSubsidyAttDao;
import top.infopub.mgr.mkt.dao.BidSubsidyDao;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.mgr.mkt.domain.BidSubsidyDomain;
import top.infopub.mgr.mkt.jsonvo.AfterSummaryJsonVo;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.model.mkt.*;
import top.infopub.mgr.mkt.service.BidSubsidyService;
import top.infopub.mgr.mkt.vo.BidSubsidyVo;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

@Service
public class BidSubsidyServiceImpl extends GenericServiceImpl<BidSubsidy, String> implements
        BidSubsidyService {

    @Autowired
    private BidSubsidyDao bidSubsidyDao;
    @Autowired
    private BidSecurityDtoDao bidSecurityDtoDao;

    @Autowired
    private BidSubsidyAttDao bidSubsidyAttDao;

    @Autowired
    private WsFlowProcessService wsFlowProcess;

    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;
    @Autowired
    private ProProcessManageService proProcessManageService;

    @Override
    public GenericDao<BidSubsidy, String> getDao() {
        return bidSubsidyDao;
    }

    @Override
    public Page<BidSubsidyDomain> selectByDomainWhere(Page<BidSubsidyDomain> page,
                                                      BidSubsidyVo bidSubsidyVo) throws ParseException {

        //处理时间范围
        if (!StringUtils.isEmpty(bidSubsidyVo.getDates())) {
            String[] splitTime = bidSubsidyVo.getDates().split("~");
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            bidSubsidyVo.setStartDate(format.parse(splitTime[0]));
            bidSubsidyVo.setEndDate(format.parse(splitTime[1]));
        }
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<BidSubsidyDomain>) bidSubsidyDao.selectByDomainWhere(bidSubsidyVo);
    }

    @Override
    public Page<BidSubsidyDomain> selectMyCheckByDomainWhere(Page<BidSubsidyDomain> page,
                                                             BidSubsidyVo bidSubsidyVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<BidSubsidyDomain>) bidSubsidyDao.selectMyCheckByDomainWhere(bidSubsidyVo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBidSubsidy(BidSubsidy bidSubsidy, List<BidSubsidyAtt> bidSubsidyAtts) {

        bidSubsidyDao.insertById(bidSubsidy);

        if (CollectionUtils.isNotEmpty(bidSubsidyAtts)) {
            bidSubsidyAttDao.insertByBatch(bidSubsidyAtts);
        }

        // 注意 这里根据不同的业务分支判断条件 获得不同enum
        FlowTemplateEnum templateEnum = FlowTemplateEnum.MKT_BID_SUBSIDY;
        // 处理工作流数据
        wsFlowProcess.launch(templateEnum, bidSubsidy.getId(), bidSubsidy.getProcessId(), null);

    }

    @Override
    public BidSubsidyVo queryById(String id) {
        return bidSubsidyDao.queryById(id);
    }

    @Override
    public void updateById(BidSubsidy subsidy, List<ProjectAttachment> attachmentList, Integer submitType, String bodyStr, AuthorizationVO vo) {

        //更新补贴信息
        bidSubsidyDao.updateByIdSelective(subsidy);
        //更新附件信息
        attach(attachmentList,subsidy);
        if (submitType == 2) {  //发起审批流程
            proProcessManageService.sendProcess(ProProcessDetailTypeEnum.PRO_NODE_TYPE13, bodyStr, subsidy.getId(), subsidy.getProCode(), vo);
        }
    }
    //更新附件信息
    protected void attach( List<ProjectAttachment> attachmentList,BidSubsidy subsidy) {
        if (attachmentList != null && attachmentList.size() > 0) {
            //批量插入附件信息
            projectAttachmentDao.deleteByWhere(subsidy.getProCode(), ProjectFileTypeEnum.FILE_TYPE39.getCode(), null);
            projectAttachmentDao.insertBatch(attachmentList);
        }
    }

    @Override
    public void insertById(BidSubsidy subsidy, List<ProjectAttachment> attachmentList, Integer submitType, String bodyStr, AuthorizationVO vo, AfterSummaryJsonVo aftSummJson) {
        //新增补贴信息
        //设置CODES
        subsidy.setCodes(IdFactory.getUUIDUpper());
        bidSubsidyDao.insertSelective(subsidy);
        //更新附件信息
        attach(attachmentList,subsidy);
        if (submitType == 2) {  //发起审批流程
            proProcessManageService.sendProcess(ProProcessDetailTypeEnum.PRO_NODE_TYPE13, bodyStr, subsidy.getId(), subsidy.getProCode(), vo);
        }
    }


    @Override
    public AfterSummaryJsonVo queryDetailById(String id) {
        //根据id查询基础信息
        AfterSummaryJsonVo summaryJsonVo = new AfterSummaryJsonVo();
        AfterSummaryDto afterSummaryDto = bidSubsidyDao.queryDetailById(id);
        //补贴信息
        BidSubsidy bidSubsidy = bidSubsidyDao.selectByPrimaryKey(id);
        summaryJsonVo.setInfo(afterSummaryDto);
        summaryJsonVo.setSubsidy(bidSubsidy);
        //附件信息
        List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(bidSubsidy.getProCode(), ProjectFileTypeEnum.FILE_TYPE39.getCode(), null);
        summaryJsonVo.setFileAtt(fileAttaListToArray(projectAttaList));
        return summaryJsonVo;
    }

    @Override
    public List<ProjectInfo> optionalProjectName() {
        return bidSubsidyDao.optionalProjectName();
    }

    @Override
    public ProjectInfo selectProjectById(String proCode) {
        return bidSecurityDtoDao.findByProCode(proCode);
    }


    private String[] fileAttaListToArray(List<ProjectAttachment> list) {
        if (list == null || list.size() <= 0) return null;
        String[] attaArr = new String[list.size()];
        int index = 0;
        for (ProjectAttachment pa : list) {
            StringBuffer tmp = new StringBuffer();
            tmp.append(pa.getSubTypes());
            tmp.append("|");
            tmp.append(pa.getFileName());
            tmp.append(pa.getFileSuffix());
            tmp.append("|");
            tmp.append(IdFactory.getUUIDSerialNumber());
            tmp.append("|");
            tmp.append(pa.getFilePath());
            attaArr[index] = tmp.toString();
            index++;
        }
        return attaArr;
    }
}
